
/*
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-21 09:16:56
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-07 06:42:31
 */
import Validator from 'validator.tool'
import { isExistUsername } from '@/api/sys/users.js'
import { isExistCode } from '@/api/goods/goods-sku.js'
const v = new Validator()

export function getValidator(path) {
  return v
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

/**
 * @param {string} str
 * @returns {Boolean}
 */
export function validUsername(str) {
  const valid_map = ['admin', 'editor']
  return valid_map.indexOf(str.trim()) >= 0
}

export const isTelOrPhone = (rule, value, callback) => {
  if (!value) return callback()
  if (!v.isPhone(value) && !v.isTel(value)) {
    return callback(new Error('请输入正确的手机或座机号!'))
  }
  callback()
}

export const isPhone = (rule, value, callback) => {
  if (!v.isPhone(String(value))) {
    return callback(new Error('请输入正确的手机号!'))
  }
  callback()
}

export const isEmail = (rule, value, callback) => {
  if (!value) return callback()
  if (!v.isEmail(value)) {
    return callback(new Error('请输入正确Email!'))
  }
  callback()
}

export const validateUsername = (rule, value, callback) => {
  if (value === '' || value === null || value === undefined) {
    return callback(new Error('用户名不能为空'))
  }
  isExistUsername(value).then(res => {
    if (res.data.code !== 200) {
      return callback(new Error(res.data.message))
    }
    callback()
  })
}

export const validateRegisterName = (rule, value, callback) => {
  if (value === '' || value === null || value === undefined) {
    return callback(new Error('用户名不能为空！'))
  }
  // if (!v.isPhone(String(value))) {
  //   return callback(new Error('请输入正确的手机号!'))
  // }
  isExistUsername(value).then(res => {
    if (!res.data.flag) {
      return callback(new Error(res.data.message))
    }
    callback()
  })
}

export const validateSkucode = (rule, value, callback) => {
  if (value === '' || value === null || value === undefined) {
    return callback(new Error('编号不能为空！'))
  }
  isExistCode(value).then(res => {
    if (!res.data.flag) {
      return callback(new Error(res.data.message))
    }
    callback()
  })
}

export const validatePassword = (rule, value, callback) => {
  if (!value) return callback(new Error('请输入密码'))
  const len = value.length
  if (len > 14 || len < 6) {
    callback(new Error('请输入6-14位密码'))
  } else {
    callback()
  }
}
